package island.gotenyama.wand.web;

import java.io.StringWriter;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.springframework.core.NestedIOException;
import org.springframework.web.servlet.view.velocity.VelocityView;

/**
 * 本システム向けVelocityViewクラス
 * 
 * @author tkawabata
 */
public class AppsVelocityView extends VelocityView {

	/**
	 * レイアウトDIR
	 */
	public static final String LAYOUT_DIR = "/WEB-INF/layout";
	
	/**
	 * デフォルト値[レイアウトURL]
	 */
	public static final String DEFAULT_LAYOUT_URL = LAYOUT_DIR + "/defaultLayout.vm";

	/**
	 * デフォルト値[レイアウトキー値]
	 */
	public static final String DEFAULT_LAYOUT_KEY = "layout";

	/**
	 * デフォルト値[メイン部分のキー値]
	 */
	public static final String DEFAULT_SCREEN_CONTENT_KEY = "screen_content";

	/**
	 * レイアウトURL
	 */
	private String layoutUrl = DEFAULT_LAYOUT_URL;

	/**
	 * レイアウトキー値
	 */
	private String layoutKey = DEFAULT_LAYOUT_KEY;

	/**
	 * メイン部分のキー値
	 */
	private String screenContentKey = DEFAULT_SCREEN_CONTENT_KEY;

	/**
	 * デリゲート
	 */
	private ViewDelegate viewDelegate;

	/**
	 * コンテキスト情報に情報を追加する。
	 * 
	 * @param コンテキスト情報
	 * @param リクエスト情報
	 * @throws Exception 例外発生時
	 */
	@Override
	protected void exposeHelpers(Context velocityContext, HttpServletRequest request) throws Exception {

		// Delegate
		final String DELEGATE_NAME = "delegate";
		velocityContext.put(DELEGATE_NAME, viewDelegate);

		// Context
		final String LAYOUT_DIR_NAME = "layoutDir";
		velocityContext.put(LAYOUT_DIR_NAME, LAYOUT_DIR);
		
		// Context
		final String CONTEXT_NAME = "context";
		velocityContext.put(CONTEXT_NAME, request.getContextPath());

		// Request
		final String REQUEST_NAME = "request";
		velocityContext.put(REQUEST_NAME, request);

		// Session
		final String SESSION_NAME = "session";
		HttpSession session = request.getSession(false);
		if (session != null) {
			velocityContext.put(SESSION_NAME, session);
		}
	}

	public void setLayoutUrl(String layoutUrl) {
		this.layoutUrl = layoutUrl;
	}

	public void setLayoutKey(String layoutKey) {
		this.layoutKey = layoutKey;
	}

	public void setScreenContentKey(String screenContentKey) {
		this.screenContentKey = screenContentKey;
	}

	public ViewDelegate getViewDelegate() {
		return viewDelegate;
	}

	public void setViewDelegate(ViewDelegate viewDelegate) {
		this.viewDelegate = viewDelegate;
	}

	@Override
	public boolean checkResource(Locale locale) throws Exception {
		if (!super.checkResource(locale)) {
			return false;
		}
		try {
			getTemplate(this.layoutUrl);
			return true;
		} catch (ResourceNotFoundException ex) {
			throw new NestedIOException("Cannot find Velocity template for URL [" + this.layoutUrl + "]: Did you specify the correct resource loader path?", ex);
		} catch (Exception ex) {
			throw new NestedIOException("Could not load Velocity template for URL [" + this.layoutUrl + "]", ex);
		}
	}

	@Override
	protected void doRender(Context context, HttpServletResponse response) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Rendering screen content template [" + getUrl() + "]");
		}
		StringWriter sw = new StringWriter();
		Template screenContentTemplate = getTemplate(getUrl());
		screenContentTemplate.merge(context, sw);

		// Put rendered content into Velocity context.
		context.put(this.screenContentKey, sw.toString());
		String layoutUrlToUse = (String) context.get(this.layoutKey);
		if (layoutUrlToUse != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Screen content template has requested layout [" + layoutUrlToUse + "]");
			}
		} else {
			layoutUrlToUse = this.layoutUrl;
		}
		mergeTemplate(getTemplate(layoutUrlToUse), context, response);
	}
}
